import {createRouter, createWebHistory} from 'vue-router'
import type { RouteRecordRaw } from 'vue-router';
import {routeGradesInit} from './routerGuards'
import {routes} from './routes';
import {_fetchRoutesFromBackend} from "@/api/generic/login/login-api.ts";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})
const fetchRoutesFromBackend = async () => {
  const response = await _fetchRoutesFromBackend();
  return response.data;
};
const modules = import.meta.glob('./../views/**/*.vue')
export const setupDynamicRoutes = async () => {
  try {
    const backendRoutes : RouteRecordRaw[] = await fetchRoutesFromBackend()
    return backendRoutes.map(route =>
      router.addRoute('default-idoo',{
        name: route.path,
        path: route.path as string,
        // meta: {
        //   KeepAlive: true
        // },
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        component:loadView(route.component as any) as any,
        props: true,
      })
    )
  } catch (error) {
    console.error('动态路由加载失败:', error)
    throw error
  }
}

export const loadView = (view : string) => {
  let res;
  console.log(modules,'modules')
  for (const path in modules) {
    const dir = path.split('views')[1];

    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
}
//grades init
routeGradesInit(router);

export default router
